package com.example.taobao

import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.activity_myorder.*
import kotlinx.android.synthetic.main.myaddress.*
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.ResponseBody
import org.json.JSONArray
import retrofit2.Call
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.create
import java.net.URLEncoder
import kotlin.concurrent.thread

class Myorder : AppCompatActivity() {
    private var orderlist:ArrayList<orderinfo> = ArrayList<orderinfo>()
       val handle = @SuppressLint("HandlerLeak")
       object : Handler()
       {
           override fun handleMessage(msg: Message) {
               orderlist.clear()
               orderlist = msg.obj as ArrayList<orderinfo>
               val layoutManager = LinearLayoutManager(this@Myorder)
               orderrecyclerview.layoutManager = layoutManager
               val adapter = OrderAdapter(orderlist)
               orderrecyclerview.adapter = adapter
               if(!orderlist.isEmpty()) {
                   orderrecyclerview.smoothScrollToPosition(orderlist.size-1)
               }
           }
       }
    fun refesh()
    {
        val layoutManager = LinearLayoutManager(this@Myorder)
        orderrecyclerview.layoutManager = layoutManager
        val adapter = OrderAdapter(orderlist)
        orderrecyclerview.adapter = adapter
        if(!orderlist.isEmpty()) {
            orderrecyclerview.smoothScrollToPosition(orderlist.size-1)
        }
        adapter.notifyDataSetChanged()
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_myorder)
        initData()
    }
    private class OrderViewHolder(view: View) : RecyclerView.ViewHolder(view)
    {
        val tvordername: TextView =view.findViewById(R.id.tv_merchandise_name)
        val tvorderprice : TextView = view.findViewById(R.id.tv_merchandise_priceq2)
        val tvtotalprice : TextView = view.findViewById(R.id.tv_merchandise_priceq5)
        val tvdescribe :TextView = view.findViewById(R.id.tv_merchandise_content)
        val tvimg :ImageView = view.findViewById(R.id.img_merchandise)
        val tvdelete : TextView =view.findViewById(R.id.tv_merchandise_button1)
    }

    private inner  class OrderAdapter(val orderlist1: List<orderinfo>) :
        RecyclerView.Adapter<OrderViewHolder>() {
        private var itemClickListener: IKotlinItemClickListener? = null
        override fun getItemCount() = orderlist1.size
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OrderViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.orderdetail, parent, false)
            return OrderViewHolder(view)
        }

        override fun onBindViewHolder(holder: OrderViewHolder, position: Int) {
            val info = orderlist1[position]
            holder.tvordername.text = info.goodsename
            holder.tvtotalprice.text = info.goodsprice
            holder.tvorderprice.text = info.goodsnum
            Glide.with(this@Myorder)
                .load(info.goodspic)
                .into(holder.tvimg)
            holder.tvdescribe.text = info.goodsdescribe
            holder.tvdelete.setOnClickListener {
                thread {
                    try {
                        val client = OkHttpClient()
                        val requestBody = FormBody.Builder()
                            .add("name", URLEncoder.encode(info.goodsename, "utf-8"))
                            .build()
                        val request = Request.Builder()
                            .url("http://192.168.43.140:8080/aaa_war_exploded/deleteorder.jsp")
                            .post(requestBody)
                            .build()
                        val respone = client.newCall(request).execute()
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
                orderlist.removeAt(position)
                refesh()
            }
            holder.itemView.setOnClickListener {
                itemClickListener
            }

        }
        fun setOnKotlinItemClickListener(itemClickListener: IKotlinItemClickListener) {
            this.itemClickListener = itemClickListener
        }

    }
    fun initData() {
        orderlist.clear()
        thread {
            try {
                var addr: ArrayList<orderinfo> = ArrayList<orderinfo>()
                val client = OkHttpClient()
                val request = Request.Builder()
                    .url("http://192.168.43.140:8080/aaa_war_exploded/getallorder.jsp")
                    .build()
                val respone = client.newCall(request).execute()
                val responeData = respone.body!!.string()
                addr = parseJosn(responeData)
                val msg = Message()
                msg.obj = addr
                handle.sendMessage(msg)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    fun parseJosn(jsonStr:String):ArrayList<orderinfo>
    {
        val address :ArrayList<orderinfo> =  ArrayList<orderinfo>()
        try {
            val jaonArray = JSONArray(jsonStr)
            for (i in 0 until jaonArray.length())
            {
                val jsonObject = jaonArray.getJSONObject(i)
                val goodsename = jsonObject.getString("goodsename")
                val goodsprice = jsonObject.getString("goodsprice")
                val goodsdescribe = jsonObject.getString("goodsdescribe")
                val goodspic = jsonObject.getString("goodspic")
                val goodsnum = jsonObject.getString("goodsnum")
                address.add(orderinfo("${goodsename}","${goodsprice}","${goodsdescribe}","${goodspic}","${goodsnum}"))
            }
        }
        catch (e: Exception)
        {
            e.printStackTrace()
        }
        return address
    }
}